package com.umall.product.service.impl;

import com.umall.product.dao.CategoryDao;
import com.umall.product.entity.CategoryEntity;
import com.umall.product.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.umall.common.utils.PageUtils;
import com.umall.common.utils.Query;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> allCategory=baseMapper.selectList(null);
        List<CategoryEntity> firstLevel=allCategory.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid()==0)
                .peek((category) -> category.setChilderCategory(getChilderCategory(category,allCategory)))
                .sorted((category1,category2) -> (category1.getSort()==null?0:category1.getSort().compareTo(category2.getSort()==null?0:category2.getSort())))
                .collect(Collectors.toList());
        return firstLevel;
    }

    public List<CategoryEntity> getChilderCategory(CategoryEntity categoryEntity,List<CategoryEntity> list){
        List<CategoryEntity> list1=list.stream()
                .filter(category ->category.getParentCid().equals(categoryEntity.getCatId()))
                .peek(category -> category.setChilderCategory(getChilderCategory(category,list)))
                .sorted((category1,category2)->(category1.getSort())==null?0:category1.getSort().compareTo(category2.getSort()==null?0:category2.getSort()))
                .collect(Collectors.toList());
        return list1.isEmpty()?null:list1;
    }
}